﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Metadata.Edm;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyAspx.EasyFramework.DAL3;
using MyAspx.EasyFramework.EntityFramework;
using MyAspx.Framework.WebUnit.CodeZipTree;
using MyAspx.Framework.Common;

namespace WebUI.Form
{
    public partial class DetailCode : System.Web.UI.Page
    {
        FileInfoDAL _fileInfoDal = new FileInfoDAL();
        ZipManage _zip = new ZipManage();
        public  commyaspxdbEntities _commyaspxdbEntities = new commyaspxdbEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
         
            //AddBrowse();
            if (!IsPostBack) {
                try
                {

                
                CurQs = Request.QueryString["guidstr"];
                Title = Titles;
                BindDetailInfo(this.CurQs);
                //先删除掉临时存储目录
                if (!Directory.Exists(Server.MapPath(@"/zipstore/")))
                {
                    Directory.CreateDirectory(Server.MapPath(@"/zipstore/"));
                }
                //Directory.Delete(MyAspx.Framework.WebUnit.CodeZipTree.PathHelper.Root, true);
                //ZipManage.Decompression(_CurFileinfo.linkurl)
                //DownUrlDAL _dal = new DownUrlDAL();
                //_dal.
                string cur_zipcodeurl =
                    _commyaspxdbEntities.my_downurl.First(query => query.downfileid == _CurFileinfo.fileid).downurl;
                string filename = new FileInfo(cur_zipcodeurl).Name.Split('.')[0].ToString();
                tempZipDir = filename;
                if (!Directory.Exists(Server.MapPath(@"/zipstore/")))
                {
                  Directory.CreateDirectory(Server.MapPath(@"/zipstore/"));
                }
                DirectoryInfo newZipDir = new DirectoryInfo(Server.MapPath(@"/zipstore/" + filename + "/"));
                if (!Directory.Exists( newZipDir.FullName))
                {
                    Directory.CreateDirectory(newZipDir.FullName);
                }
                ZipManage.Decompression(Server.MapPath(cur_zipcodeurl),newZipDir.FullName,true);
                }
                catch (Exception )
                {
                    //MessageBox.LayerShow(this.Page,"源码没有解压文件，获取源码树失败。");
                    MessageBox.ResponseScript(this.Page, "$('.fileTree').html('" + "源码没有解压文件，获取源码树失败。" + "');");
                    //throw;
                }
            }
            AddBrowse();
        }
        public string tempZipDir { get; set; }
        public string DetailTitle { get; set; }
        public string DetailPic { get; set; }
        public string DetailDes { get; set; }
        public string CurQs { get; set; }
        public string Titles
        {
            get { return _CurFileinfo.filename + "  源码更新于：" + _CurFileinfo.addtime + " - .net源码|- MyAspx.com"; }
        }
        public string DownUrl
        {
            get
            {
                var data = _commyaspxdbEntities.my_downurl.Where(p => p.downfileid == _CurFileinfo.fileid);
                if (data.Count() > 0)
                    return "http://" + Request.Url.Host + ":" + Request.Url.Port +
                           (data.First().downurl.Replace("~", ""));
                else
                    return "";
            }
        }

        [Description("当前code的详情信息对象实例")]
        public my_fileinfo _CurFileinfo {
            get
            {
                var _curFileInfo =
                    _fileInfoDal.GetMyFileinfoByGuid(this.CurQs);
                //if (_curFileInfo != null) 
                    return _curFileInfo;
            }
        }
        public void BindDetailInfo(string codeGuid)
        {
            var _curFileInfo =_fileInfoDal.GetMyFileinfoByGuid(codeGuid);
            this.DetailTitle = _curFileInfo.filename;
            DetailPic = _curFileInfo.filefirimg;
            this.DetailDes = _curFileInfo.codedes;
        }

        public int RenderUiAndOutData(Func<my_fileinfo> tAction, string key,my_fileinfo _myFileinfo)
        {
            //tAction.
            return -1;
            //tAction.BeginInvoke(_myFileinfo,tAction.GetObjectData(SerializableAttribute.IsDefined()))
        }

        public IEnumerable<string> tagNameList
        {
            get
            {  
                //string temp ="<span style="color: gray;font-size: 7px; margin-top: 0px; margin-bottom: -1px;">标签：<%# Server.HtmlDecode(Eval("tagname").ToString())%></span>
                string cmd = SqlDataSource1.SelectCommand.Insert(SqlDataSource1.SelectCommand.LastIndexOf("ORDER"),
                    " where a.fileid = '" + _CurFileinfo.fileid + "' ");
                DataTable dt = _fileInfoDal.@select(cmd);
                foreach (DataRow dr in dt.Rows)
                {
                    yield return dr["tagname"].ToString();
                }

                //
               
            }
        }

        public string CodeClassName
        {
            get
            {
               // _commyaspxdbEntities.my_class.Where(clas=>clas.classid ==_CurFileinfo.fileclassid).First().classname 
                if (_commyaspxdbEntities.my_class.Where(clas => clas.classid == _CurFileinfo.fileclassid).Count() > 0)
                {
                    return
                        _commyaspxdbEntities.my_class.Where(clas => clas.classid == _CurFileinfo.fileclassid)
                            .First()
                            .classname;
                }
                else
                {
                    return "暂无分类";
                }
            }
        }
        private string _saletype = "";
        /// <summary>
        /// 销售类型
        /// </summary>
        public string SaleType
        {
            get
            {

                try
                {
                    var stquery = /*from*/ _CurFileinfo.saletypeid;
                    switch (stquery)
                    {
                        case 1:
                            _saletype = "免费";
                            break;
                        case 2:
                            _saletype = "积分";
                            var salenub =
                                _commyaspxdbEntities.my_saledetail.Where(sd => sd.fileid == _CurFileinfo.fileid)
                                    .First()
                                    .salenum;
                            _saletype = "积分:" + salenub;
                            break;
                        case 4:
                            _saletype = "人民币";
                            var salenub2 =
                             _commyaspxdbEntities.my_saledetail.Where(sd => sd.fileid == _CurFileinfo.fileid)
                                 .First()
                                 .salenum;
                            _saletype = "人民币￥:" + salenub2;

                            break;
                        case 3:
                            _saletype = "人民币";
                            var salenub3 =
                              _commyaspxdbEntities.my_saledetail.Where(sd => sd.fileid == _CurFileinfo.fileid)
                                  .First()
                                  .salenum;
                            _saletype = "人民币￥:" + salenub3;
                            break;
                    }
                 
                }
                catch (Exception) { }
                //RenderUiAndOutData(new Action<my_fileinfo>(), )
                //object @from;
                 return _saletype;
            }
        }

        private string _salybasetype = "";

        public string SalyBaseType
        {
            get
            {

                try
                {
                    var stquery = _CurFileinfo.saletypeid;
                    switch (stquery)
                    {
                        case 1:
                            _salybasetype = "免费";
                            break;
                        case 2:
                            _salybasetype = "积分";
                            break;
                        case 4:
                            _salybasetype = "人民币";

                            break;
                        case 3:
                            _salybasetype = "人民币";
                            break;
                    }

                }
                catch (Exception) { }
                return _salybasetype;
            }
        }
        public string[] ImageLists
        {
            get
            {
                string ils = _CurFileinfo.filepics;
                ils = ils.Replace("<br>", ",");
                ils = ils.Replace("~", "");
                string[] ilsImgs = ils.Split(',');
                return ilsImgs;

            }
        }

        public string[] UserData
        {
            get
            {
                string un="", pic = "";
                try
                {
                    //string sessionUser = Session["myaspxuser"].ToString();
                    var data = _commyaspxdbEntities.my_usercodererelation.Where(q => q.fileid == _CurFileinfo.fileid).First().userid;
                    un = _commyaspxdbEntities.my_users.Where(p => p.userid == data).First().useregname;
                    pic = _commyaspxdbEntities.my_users.Where(p => p.userid == data).First().uselogopic;

                }
                catch (Exception)
                {

                    un = "网站超管";
                    pic = "/images/avater/d7.png";
                  
                }
                return new[] {un, pic};
            }
        }
        public string img1
        {
            get
            {
                if (ImageLists.Length >= 3)
                {
                    return ImageLists.First();
                }
                else
                {
                    return _CurFileinfo.filefirimg;
                }
            }
        }
        public string img2
        {
            get
            {
                if (ImageLists.Length >= 3)
                {
                    return ImageLists[1];
                }
                else
                {
                    if (ImageLists.Length >= 2)
                    {
                        return ImageLists[1];
                    }
                    else
                    {
                        return _CurFileinfo.filefirimg;
                    }
                    
                }
            }
        }

        public string img3
        {
            get
            {
                if (ImageLists.Length >= 3)
                {
                    return ImageLists[2];
                }
                else
                {
                    if (ImageLists.Length >= 3)
                    {
                        return ImageLists[2];
                    }
                    if (ImageLists.Length >= 2)
                    {
                        return ImageLists[1];
                    }
                    else
                    {
                        return _CurFileinfo.filefirimg;
                    }

                }
            }
        }

        public string UsgMesg
        {
            get
            {
                var um = _CurFileinfo.usermsg;

                return um != null && um.Length>53 ?  _CurFileinfo.usermsg.Substring(0, 53):um;
            }
        }
        public string CurCodeUpLoaderActionLastDateTime
        {
            get
            {
                string result = "";
                if (_commyaspxdbEntities.my_usercodererelation.Where(count =>
                    count.fileid == _CurFileinfo.fileid).Count() != 0)
                {
                    int userid = (int) _commyaspxdbEntities.my_usercodererelation.Where(count =>
                        count.fileid == _CurFileinfo.fileid).FirstOrDefault().userid;
                    string userName =
                        _commyaspxdbEntities.my_users.Where(
                            u => u.userid == (_commyaspxdbEntities.my_usercodererelation.Where(count =>
                                count.fileid == _CurFileinfo.fileid).FirstOrDefault().userid)).First().useregname;
                    //switch (userName)
                    //{
                    //    case 
                    //}
                    if (userName == "sys")
                    {
                        result = DateTime.Now.ToString();
                    }
                    else
                    {
                        result = _commyaspxdbEntities.my_logindetail.Where(p => p.loginuserid == userid

                            ).OrderByDescending(s => s.loginTime).First().loginTime.ToString();
                    }

                }
                else
                {
                     result =DateTime.MinValue.ToString();
                }
                return result;
            }
        }
        public int curUserPubCodeCount()
        {
          return  _commyaspxdbEntities.my_usercodererelation.Where(q => 
              q.userid == (_commyaspxdbEntities.my_usercodererelation.Where(count => 
                  count.fileid == _CurFileinfo.fileid).FirstOrDefault().userid)).Count();
           
        }
        public List<CommentFormat> CommentLists
        {
            get
            {
                List<CommentFormat> _commentFormats = new List<CommentFormat>();
                //_commentFormats.Add();
                var ls = _commyaspxdbEntities.my_comment.Where(query => query.codefileid == _CurFileinfo.fileid && query.pid == null).OrderByDescending(t=>t.commenttime);
                //ls.ToList().ForEach(f=>new Action<bool>(delegate
                //{
                //    yield return f;
                //}));
                 //ls.
                foreach (my_comment myComment in ls)
                {
                    string un = "游客";
                    string pic = "";
                    int count2 = 0;
                    try
                    {
                       un =
                        _commyaspxdbEntities.my_users.Where(i => i.userid == myComment.userid).First().useregname;
                       pic   =
                        _commyaspxdbEntities.my_users.Where(i => i.userid == myComment.userid).First().uselogopic;
                        count2 = _commyaspxdbEntities.my_comment.Where(q => q.pid == myComment.id).Count();

                    }
                    catch (Exception)
                    {

                        un = "游客";
                        pic = "/images/avater/d1.png";
                        count2 = _commyaspxdbEntities.my_comment.Where(q => q.pid == myComment.id).Count();
                    }
                    string comment2context = "";
                    if (count2 > 0)
                    {
                        foreach (my_comment curComment in _commyaspxdbEntities.my_comment.Where(ba => ba.pid == myComment.id && ba.codefileid == myComment.codefileid))
                        {
                            string un2 = "游客";
                            string pic2 = "";
                            try
                            {
                                un2 =
                                 _commyaspxdbEntities.my_users.Where(us => us.userid == curComment.userid).FirstOrDefault().useregname;
                                pic2 =
                                 _commyaspxdbEntities.my_users.Where(us => us.userid == curComment.userid).FirstOrDefault().uselogopic;


                            }
                            catch (Exception)
                            {

                                un2 = "游客";
                                pic2 = "/images/avater/d1.png";
                            }
                               string tempstr =
                            " <div class=\"clearfix comment2base alert alert-success alert-dismissable\" style=\"margin-left:20px;\"><input type=\"hidden\" class=\"commentid\" value=\"" +
                            curComment.id + "\" /><div class=\"fl head_portrait\"><img src=\"" +pic2  +
                            "\" width=\"30\" height=\"30\" style=\"width:30px;height:30px\" alt=\"\"> </div><div class=\"fl discuss_list_con\"><div class=\"discuss_list_con_tit\"><span class=\"commentusername\">" +
                            un2+ "</span><span class=\"commentuseraddtime2\">发表于：" +
                            curComment.commenttime + "</span></div><p>" + curComment.commentcontent + "</p>" +
                            "</div>" +
                            "</div>";
                            comment2context += tempstr;
                        }
                        
                     
                    }
                    else
                    {
                        
                    }
                    CommentFormat curFormat = new CommentFormat()
                    {
                        CommentAddTime = (DateTime) myComment.commenttime,
                        Content = myComment.commentcontent,
                        UserName = un,
                        UserPic = pic,
                        cid = myComment.id,
                        c2count = count2,
                        c2comment = comment2context
                    };
                    _commentFormats.Add(curFormat); ;
                }
                return _commentFormats;
            }
        } 
        public decimal CodeZipLength
        {
            get
            {
                try
                {
                    string cur_zipcodeurl =Server.MapPath(_commyaspxdbEntities.my_downurl.
                    First(
                         query => 
                             query.downfileid == _CurFileinfo.fileid).downurl);
                    return decimal.Parse((new FileInfo(cur_zipcodeurl).Length/1024/1024).ToString()) ;
                }
                catch (Exception)
                {

                    return -1;
                }
             
               
            }
        }
        private string _codetype = "";
        public string CodeType
        {
            get
            {
                //RenderUiAndOutData(new Action<my_fileinfo>(), )
                //object @from;
                var stquery = /*from*/ _CurFileinfo.codetype;
                switch (stquery)
                {
                    case "1":
                        _codetype = "C/S";
                        break;
                    case "2":
                        _codetype = "B/S";
                        break;
                    case "3":
                        _codetype = "其他";
                        break;
                }
                return _codetype;
            }
        }


        public List<string[]> get5CodeFileInfoByCodeClass()
        {
            //#3bafda
            #region 代码查找、根据类别
            List<string[]> _list = new List<string[]>();
            var curClassID = _CurFileinfo.fileclassid;
            var fileInfos = _commyaspxdbEntities.my_fileinfo.Where(
                code => code.fileclassid == curClassID
                ).OrderByDescending(c => c.addtime).Take(5);
             fileInfos.ToList().ForEach(
                 (f) =>
                 {
                     int? count = 0;
                     if (_commyaspxdbEntities.my_browse.Where(fa => fa.fileid == f.fileid).Count() > 0)
                     {
                         count = _commyaspxdbEntities.my_browse.Where(fa => fa.fileid == f.fileid).First().browsecount ;
                     }
                     
                     string[] curdata = new string[]
                     {
                         f.filename,
                         f.createuser,
                         f.filefirimg,
                         count.ToString(),
                         f.fileid
                     };
                     _list.Add(curdata);
                 }
                 );
            return _list;

            #endregion
        } 
        public List<String[] >get3ListCurCodeUpLoadCodeRandom()
        {
            string codeUpLoadName = UserData[0].ToString();
            List<string[] >resultdata = new List<string[]>();
            try
            {
                int userid = _commyaspxdbEntities.my_users.First(f => f.useregname == codeUpLoadName).userid;
                var codeList = _commyaspxdbEntities.my_usercodererelation
                    .Where(query => query.userid == userid).Distinct().OrderByDescending(d => d.id);
                codeList.ToList().ForEach(
                    (lf)
                        =>
                    {
                        //数据填充
                        my_fileinfo _cFileinfo = _commyaspxdbEntities.my_fileinfo.Where(
                            result => result.fileid == lf.fileid
                            ).First();
                        string fn = _cFileinfo.filename;
                        string fid = lf.fileid;
                        string fntime = DateTime.Parse( _cFileinfo.addtime).ToShortDateString();
                        string st = "";
                        var stquery = /*from*/ _cFileinfo.saletypeid;
                        switch (stquery)
                        {
                            case 1:
                                st = "免费";
                                break;
                            case 2:
                                st = "积分";
                                //var salenub = _commyaspxdbEntities.my_saledetail.Where(sd=>
                                //    sd.fileid == cu)
                                break;
                            case 4:
                                st = "金币";
                                break;
                            case 3:
                                st = "金币";
                                break;
                        }
                        string pic = _cFileinfo.filefirimg;
                        string[] curStrings = new[] { fn, fntime, st,pic,fid };
                        resultdata.Add(curStrings);
                    }
                    );
            }
            catch(Exception){}
            return resultdata;
        }
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
        }

        /// <summary>
        /// 浏览记录加1
        /// </summary>
        public void AddBrowse()
        {
            try
            {
                my_browse stud = new my_browse();

                if (_commyaspxdbEntities.my_browse.Count(f => f.fileid == _CurFileinfo.fileid) > 0)
                {
                    stud =
                        _commyaspxdbEntities.my_browse.Where(s => s.fileid == _CurFileinfo.fileid)
                            .First<my_browse>();
                }
                else
                {
                    _commyaspxdbEntities.my_browse.Add(new my_browse()
                    {
                        browsecount = 1,
                        browser = Request.Browser.Platform.ToString(),
                        fileid = _CurFileinfo.fileid,
                        ip = Request.UserHostAddress.ToString()
                    });
                    _commyaspxdbEntities.SaveChanges();
                }


                // change student name in disconnected mode (out of DBContext scope)
                if (stud != null)
                {
                    stud.browsecount += 1;
                    _commyaspxdbEntities.Entry(stud).State = System.Data.Entity.EntityState.Modified;
                    _commyaspxdbEntities.SaveChanges();
                }
                else
                {
                    _commyaspxdbEntities.my_browse.Add(new my_browse()
                    {
                        browsecount = 1,
                        browser = Request.Browser.Platform.ToString(),
                        fileid = _CurFileinfo.fileid,
                        ip = Request.UserHostAddress.ToString()
                    });
                    _commyaspxdbEntities.SaveChanges();
                }
            }
            catch (Exception)
            {
                
                
            }
            //_commyaspxdbEntities.my_browse.Add(new my_browse()
            //{
                
            //});
            //var bc = _commyaspxdbEntities.my_browse.Where(f => f.fileid == _CurFileinfo.fileid).First().browsecount;
            //_commyaspxdbEntities.my_browse.Remove(new my_browse() {fileid = _CurFileinfo.fileid});
            //_commyaspxdbEntities.SaveChanges();
            //bc += 1;
          
            //save modified entity using new DBContext
            
                //Mark entity as modified： 这里采用entity的主键进行匹配。因此，采用这种方法时，必须确保主键已经设置。
             
            
        }

        public void AddBrowerOne()
        {
            _commyaspxdbEntities.my_browse.Add(new my_browse()
            {
                browsecount = 1,
                browser = Request.Browser.Platform.ToString(),
                fileid = _CurFileinfo.fileid,
                ip = Request.UserHostAddress.ToString()
            });
            _commyaspxdbEntities.SaveChanges();
        }
        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
            //MessageBox.Show(this,"页面关闭");
            if (Directory.Exists(Server.MapPath(@"/zipstore/")))
            {
                //Directory.Delete(MyAspx.Framework.WebUnit.CodeZipTree.PathHelper.Root, true);
            }
        }
    }
}